package com.njwd.rpc.expand;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.rpc.Invocation;
import com.alibaba.dubbo.rpc.Invoker;
import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.dubbo.rpc.cluster.Router;
import com.alibaba.dubbo.rpc.cluster.router.condition.ConditionRouter;

public class CustomerParamRoute implements Router {
	private static final Logger logger = LoggerFactory
			.getLogger(CustomerParamRoute.class);

	private final int priority;
	private URL url;

	public CustomerParamRoute(URL url) {
		this.url = url;
		this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
	}

	@Override
	public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url,
			Invocation invocation) throws RpcException {
		Object[] arguments = invocation.getArguments();
		if (arguments == null || arguments.length == 0) {
			logger.error("method:" + invocation.getMethodName()
					+ " do not have route param");
			return null;
		}
		if(invokers == null || invokers.size()==0){
			return null;
		}
		Object routeKey = arguments[0];
		List<Invoker<T>> result = new ArrayList<Invoker<T>>();
		for (Invoker<T> invoker : invokers) {
			String group = invoker.getUrl().getParameter(Constants.GROUP_KEY);
			if (routeKey.equals(group)) {
				result.add(invoker);
				return result;
			}
		}
		result.add(invokers.get(0));
		return result;
	}

	@Override
	public int compareTo(Router o) {
		if (o == null || o.getClass() != CustomerParamRoute.class) {
			return 1;
		} else {
			CustomerParamRoute c = (CustomerParamRoute) o;
			return this.priority == c.priority ? url.toFullString().compareTo(
					c.url.toFullString()) : (this.priority > c.priority ? 1
					: -1);
		}
	}

	@Override
	public URL getUrl() {
		// TODO Auto-generated method stub
		return url;
	}

}
